package com.wechart.service.user.impl;


import com.wechart.controller.Auth;
import com.wechart.dao.domain.AreainfoCriteria;
import com.wechart.dao.domain.Userinfo;
import com.wechart.dao.domain.UserinfoCriteria;
import com.wechart.dao.mapper.AreainfoMapper;
import com.wechart.dao.mapper.UserinfoMapper;
import com.wechart.model.AuthModel;
import com.wechart.service.user.AuthService;
import com.wechart.utils.DateUtil;
import com.wechart.utils.MD5Encrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by SUNZZ on 2017/2/13.
 */

@Service("authService")
public class AuthServiceImpl implements AuthService {


    @Autowired
    private UserinfoMapper userinfoMapper;

    @Autowired
    private AreainfoMapper areainfoMapper;

//    @Override
//    public Auth getUser(String username){
//        UserCriteria criteria = new UserCriteria();
//
//        criteria.createCriteria().andNameEqualTo(username);
//
//        List<User> users = userMapper.selectByExample(criteria);
//
//        Auth auth = new Auth();
//
//        auth.setUsers(users);
//
//        if (!CollectionUtils.isEmpty(users)){
//            auth.setReturnCode("1");
//            return auth;
//        }
//        return null;
//    }

    /**
     * 用户更新状态
     * @param auth
     * @param i
     * @return
     */
    @Override
    public int updateUserState(Auth auth, short i){
        UserinfoCriteria criteria = new UserinfoCriteria();

        UserinfoCriteria.Criteria userCriteria = criteria.createCriteria();

        List<Userinfo> result;

//        Userinfo result;
        Userinfo userinfo = auth.getUser();

        if (StringUtils.isNotEmpty(userinfo.getUsername())){
            userCriteria.andUseridEqualTo(userinfo.getUserid());
        }

//        result = userinfoMapper.selectByExample(criteria);

        result = userinfoMapper.selectByExample(criteria);
        if (CollectionUtils.isEmpty(result)){
            return userinfoMapper.insert(userinfo);
        } else {
            if (i==1){
//                Short i =1;
                userinfo.setUserstate(i);
                userinfo.setLastlogin(new Date(System.currentTimeMillis()));
            }else{
//                Short i =0;
                userinfo.setUserstate(i);
                userinfo.setLastlogout(new Date(System.currentTimeMillis()));
            }
            return  userinfoMapper.updateByExampleSelective(userinfo,criteria);
        }
    }

    /**
     * 用户修改密码
     * @param auth
     * @param psd
     * @return
     */
    @Override
    public int passwd(Auth auth , String psd){
        UserinfoCriteria criteria = new UserinfoCriteria();

        UserinfoCriteria.Criteria userCriteria = criteria.createCriteria();

//        Userinfo result;
        Userinfo userinfo = auth.getUser();

        if (StringUtils.isNotEmpty(userinfo.getUsername())){
            userCriteria.andUseridEqualTo(userinfo.getUserid());
        }

//        result = userinfoMapper.selectByExample(criteria);

        List<Userinfo> result = userinfoMapper.selectByExample(criteria);
        if (CollectionUtils.isEmpty(result)){
            return userinfoMapper.insert(userinfo);
        } else {
            if (userinfo.getUserstate()==1){
                Short i =0;
                userinfo.setUserstate(i);
                userinfo.setPassword(psd);
                userinfo.setLastlogout(new Date(System.currentTimeMillis()));
            }
            return  userinfoMapper.updateByExampleSelective(userinfo,criteria);
        }
    }

    /**
     * 用户全查询
     * @return
     */
    @Override
    public List<Userinfo> getAllUsers(String area){
        UserinfoCriteria userinfoCriteria = new UserinfoCriteria();
        UserinfoCriteria.Criteria criteria = userinfoCriteria.createCriteria();

        if (null!=area && area!="3300") {
            criteria.andAreacodeEqualTo(area);
        }

        List<Userinfo> data = new ArrayList<>();
        for(Userinfo userinfo:userinfoMapper.selectByExample(userinfoCriteria)){
            AreainfoCriteria ac = new AreainfoCriteria();
            ac.createCriteria().andCodeEqualTo(userinfo.getAreacode());
//            String name = areainfoMapper.selectByExample(ac).get(0).getName();
            userinfo.setAreacode(areainfoMapper.selectByExample(ac).get(0).getName());
            data.add(userinfo);

        }
        return data;
    }

    /**
     * 用户ID查询
     * @return
     */
    @Override
    public Userinfo selectAllUsersById(String id){
        UserinfoCriteria criteria = new UserinfoCriteria();
        criteria.createCriteria().andIdEqualTo(Integer.parseInt(id));
        return userinfoMapper.selectByExample(criteria).get(0);
    }

    /**
     * 登陆使用
     * 0成功
     * 1用户不存在
     * 2密码不对
     * 3用户已登陆
     * @param id
     * @param pwd
     * @return
     */
    @Override
    public Auth getUserByIdAndPwd(String id,String pwd){

        UserinfoCriteria criteria = new UserinfoCriteria();
        criteria.createCriteria().andUseridEqualTo(id);
        List<Userinfo> users = userinfoMapper.selectByExample(criteria);


        Auth auth = new Auth();
        String encryptPwd= MD5Encrypt.encrypt(pwd);
        if (!CollectionUtils.isEmpty(users)){
            auth.setUser(users.get(0));
            if (users.get(0).getUserstate()==0) {
                if (users.get(0).getPassword().equals(encryptPwd)){
                    auth.setReturnCode(0);
                    return auth;
                } else {
                    auth.setReturnCode(2);
                    return auth;
                }
            }else{
                auth.setReturnCode(3);
                return auth;
            }

        }else{
            auth.setReturnCode(1);
            return auth;
        }
    }


    /**
     * 用户插入
     * @param authModel
     * @return
     */
    @Override
    public int insertUser(AuthModel authModel){
        UserinfoCriteria userinfoCriteria = new UserinfoCriteria();
        userinfoCriteria.createCriteria().andUseridEqualTo(authModel.getUserid());

        if (userinfoMapper.selectByExample(userinfoCriteria).size()!=0){
            return 3;
        }else {

            Userinfo data = new Userinfo();
            data.setUserid(authModel.getUserid());
            data.setUsername(authModel.getUsername());
            data.setPassword(MD5Encrypt.encrypt(authModel.getPassword()));
            data.setRole(Short.valueOf(authModel.getRole()));
            data.setPermission(authModel.getPermission());
            data.setAreacode(authModel.getAreacode());
            data.setExpiredate(StringUtils.remove(authModel.getExpiredate(), "-"));
            data.setUserstate(Short.valueOf(authModel.getUserstate()));
            data.setCreatedate(DateUtil.formate(new Date(System.currentTimeMillis()), "SHORT"));
            return userinfoMapper.insertSelective(data);
        }
    }

    /**
     * 用户修改
     * @param authModel
     * @return
     */
    @Override
    public int modifyUser(String id ,AuthModel authModel){
        UserinfoCriteria userinfoCriteria = new UserinfoCriteria();
        userinfoCriteria.createCriteria().andIdEqualTo(Integer.parseInt(id));
        Userinfo data = new Userinfo();

        data.setUserid(authModel.getUserid());
        data.setUsername(authModel.getUsername());
        data.setPassword(authModel.getPassword());
        data.setRole(Short.valueOf(authModel.getRole()));
        data.setPermission(authModel.getPermission());
        data.setAreacode(authModel.getAreacode());
        data.setExpiredate(StringUtils.remove(authModel.getExpiredate(),"-"));
        data.setUserstate(Short.valueOf(authModel.getUserstate()));
//        data.setCreatedate(DateUtil.formate(new Date(System.currentTimeMillis()),"SHORT"));
        return userinfoMapper.updateByExampleSelective(data,userinfoCriteria);
    }

    /**
     * 首次登陆插入系统管理员
     * @return
     */
    @Override
    public void insertAdmin(String pwd){
        Userinfo data = new Userinfo();
        data.setUserid("123");
        data.setUsername("admin");
        data.setPassword(MD5Encrypt.encrypt(pwd));
        data.setRole(Short.parseShort("1"));
        data.setPermission("1");
        data.setAreacode("3300");
        data.setExpiredate("20990101");
        data.setUserstate(Short.valueOf("0"));
        data.setCreatedate(DateUtil.formate(new Date(System.currentTimeMillis()),"SHORT"));
        userinfoMapper.insertSelective(data);
    }

    /**
     * 统计用户的数量
     * @return
     */
    @Override
    public int countUser() {
        UserinfoCriteria userinfoCriteria = new UserinfoCriteria();
        UserinfoCriteria.Criteria criteria = userinfoCriteria.createCriteria();
        List<Userinfo> data = new ArrayList<>();
        return userinfoMapper.selectByExample(userinfoCriteria).size();
    }
}
